package com.getpebble.android.onboarding.activity;

import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.widget.Toast;
import com.getpebble.android.PebbleApplication;
import com.getpebble.android.R;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.common.core.util.PblPreferences;
import com.getpebble.android.common.core.util.PblPreferences.PrefKey;
import com.getpebble.android.common.model.FirmwareVersion;
import com.getpebble.android.common.model.PblDevice;
import com.getpebble.android.common.model.PblDeviceModel.PblDeviceRecord;
import com.getpebble.android.connection.ConnectionManagerFragment;
import com.getpebble.android.core.PblBaseActivity;
import com.getpebble.android.framework.developer.PblDeviceObserver.ConnectedDeviceChangeListener;
import com.getpebble.android.framework.util.PebbleCapabilities;
import com.getpebble.android.framework.util.PebbleCapabilities.ConnectedDevice;
import com.getpebble.android.main.activity.MainActivity;
import com.getpebble.android.main.sections.appstore.fragment.NoConnectivityFragment;
import com.getpebble.android.main.sections.settings.fragment.LanguageSelectionStartFragment;
import com.getpebble.android.onboarding.OnboardingPreferences;
import com.getpebble.android.onboarding.fragment.AppCheckUpdateFragment;
import com.getpebble.android.onboarding.fragment.EnableNotificationsFragment;
import com.getpebble.android.onboarding.fragment.FirmwareUpdateFragment;
import com.getpebble.android.onboarding.fragment.PebbleOnlyFragment;
import com.sun.mail.imap.protocol.ListInfo;
import com.sun.mail.smtp.SMTPMessage;
import java.util.Arrays;

public class OnboardingActivity extends PblBaseActivity {
    private static final int[] ONBOARDING_SEQUENCE_LANGUAGE_SELECTION = new int[]{2};
    private static final int[] ONBOARDING_SEQUENCE_MIGRATION = new int[]{1, 2, 3};
    private static final int[] ONBOARDING_SEQUENCE_NEW_USER = new int[]{1, 2, 3, 4};
    private static final int[] ONBOARDING_SEQUENCE_PRF = new int[]{1, 2};
    public static final String TAG = OnboardingActivity.class.getSimpleName();
    private final ConnectedDeviceChangeListener mDeviceChangeListener = new ConnectedDeviceChangeListener() {
        public void notifyConnectedDeviceChanged() {
            OnboardingActivity.this.mHandler.post(new Runnable() {
                public void run() {
                    if (OnboardingActivity.this.mIsRebooting) {
                        if (PebbleApplication.getConnectedDevice() != null) {
                            OnboardingActivity.this.mIsRebooting = false;
                        }
                    } else if (PebbleApplication.getConnectedDevice() == null && !OnboardingActivity.this.mInWatchSelector) {
                        OnboardingActivity.this.redirectToConnectionManager();
                    }
                }
            });
        }
    };
    private Handler mHandler = new Handler(Looper.getMainLooper());
    private boolean mHasPostResumed = false;
    private boolean mInConnectionManager = false;
    private boolean mInWatchSelector = false;
    private boolean mIsInErrorState = false;
    private boolean mIsRebooting = false;
    private int[] mOnboardingSequence = ONBOARDING_SEQUENCE_NEW_USER;
    private int mOnboardingStepIndex = 0;
    private Runnable mPostResumeRunnable = null;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        hideActionBar();
        if (savedInstanceState != null) {
            this.mOnboardingStepIndex = savedInstanceState.getInt("extra_onboarding_step", 0);
            Trace.verbose(TAG, "Got onboarding step index from saved instance state: " + this.mOnboardingStepIndex);
            this.mOnboardingSequence = savedInstanceState.getIntArray("EXTRA_ONBOARDING_SEQUENCE");
        }
        int[] onboardingSequence = getOnboardingSequence();
        if (onboardingSequence == null) {
            Trace.error(TAG, "Onboarding sequence was null; a race condition may have occurred where Pebble disconnected. Creating a zero-length sequence and bailing out");
            this.mOnboardingSequence = new int[0];
            this.mIsInErrorState = true;
            return;
        }
        Trace.debug(TAG, "Got onboarding sequence: " + Arrays.toString(this.mOnboardingSequence));
        if (!Arrays.equals(this.mOnboardingSequence, onboardingSequence)) {
            Trace.error(TAG, "Onboarding sequence from saved instance state does not match most recently determined onboarding state. State may have changed while the activity was closed.");
            Trace.error(TAG, "Invalidating the onboarding step by setting it to zero and using the recently determined sequence; ignoring the saved instance state.");
            this.mOnboardingStepIndex = 0;
            this.mOnboardingSequence = onboardingSequence;
            Trace.warning(TAG, String.format("Using sequence %s", new Object[]{Arrays.toString(this.mOnboardingSequence)}));
        }
        switchFragment(getFragmentByStep());
    }

    public void onStart() {
        super.onStart();
        PebbleApplication.onActivityOnStart();
    }

    public void onPostResume() {
        super.onPostResume();
        Trace.verbose(TAG, "onPostResume()");
        this.mHasPostResumed = true;
        PebbleApplication.addConnectedDeviceChangeListener(this.mDeviceChangeListener);
        if (PebbleApplication.getConnectedDevice() == null) {
            if (new PblPreferences(this).getBooleanData(PrefKey.USER_SEEN_PEBBLE_ONLY_SCREEN, false)) {
                redirectToConnectionManager();
                return;
            }
            Trace.verbose(TAG, "Redirecting to watch selector (user is disconnected and has not seen this before)");
            this.mInWatchSelector = true;
            switchFragment(new PebbleOnlyFragment());
        } else if (this.mIsInErrorState) {
            Trace.error(TAG, "Bailing out of onboarding activity; was in error state");
            exit();
        } else if (this.mPostResumeRunnable != null) {
            Trace.debug(TAG, "onPostResume: Running event scheduled for after onPostResume");
            this.mHandler.post(this.mPostResumeRunnable);
            this.mPostResumeRunnable = null;
        }
    }

    public void onSaveInstanceState(Bundle outState) {
        Trace.verbose(TAG, "Saving onboarding step: " + this.mOnboardingStepIndex);
        outState.putInt("extra_onboarding_step", this.mOnboardingStepIndex);
        Trace.verbose(TAG, "Saving onboarding sequence: " + Arrays.toString(this.mOnboardingSequence));
        outState.putIntArray("EXTRA_ONBOARDING_SEQUENCE", this.mOnboardingSequence);
        super.onSaveInstanceState(outState);
    }

    public void onPause() {
        super.onPause();
        this.mHasPostResumed = false;
        PebbleApplication.removeConnectedDeviceChangeListener(this.mDeviceChangeListener);
    }

    public void onStop() {
        super.onStop();
        PebbleApplication.onActivityOnStop();
    }

    public void onBackPressed() {
    }

    public void onReboot() {
        this.mIsRebooting = true;
    }

    public void onRebootTimeout() {
        if (PebbleApplication.getConnectedDevice() == null) {
            redirectToConnectionManager();
        }
    }

    public void goToNextScreen() {
        this.mOnboardingStepIndex++;
        if (currentStep() == 2 && !ConnectedDevice.isLanguageSupported()) {
            Trace.error(TAG, "Onboarding a pre-2.8 Pebble. Language setup occurs after FW updating, so this should not happen!");
            this.mOnboardingStepIndex++;
        }
        showCurrentScreen();
    }

    public void showCurrentScreen() {
        this.mPostResumeRunnable = new Runnable() {
            public void run() {
                if (OnboardingActivity.this.mInWatchSelector && PebbleApplication.getConnectedDevice() == null) {
                    OnboardingActivity.this.mInWatchSelector = false;
                    OnboardingActivity.this.redirectToConnectionManager();
                    return;
                }
                Fragment nextFragment = OnboardingActivity.this.getFragmentByStep();
                OnboardingActivity.this.mInConnectionManager = false;
                if (nextFragment == null) {
                    OnboardingPreferences.setOnboardingVersion(PebbleApplication.getConnectedDevice(), 1);
                    OnboardingActivity.this.setResult(-1);
                    OnboardingActivity.this.exit();
                    return;
                }
                OnboardingActivity.this.switchFragment(nextFragment);
            }
        };
        if (this.mHasPostResumed) {
            Trace.verbose(TAG, "showCurrentScreen(): onPostResume has run already");
            this.mHandler.post(this.mPostResumeRunnable);
            this.mPostResumeRunnable = null;
            return;
        }
        Trace.debug(TAG, "showCurrentScreen(): onPostResume has not run yet - event scheduled to occur after onPostResume.");
    }

    private void exit() {
        startActivity(new Intent(this, MainActivity.class));
        finish();
    }

    public Fragment getFragmentByStep() {
        Trace.debug(TAG, "Getting fragment for: " + this.mOnboardingStepIndex);
        switch (currentStep()) {
            case SMTPMessage.RETURN_FULL /*1*/:
                return new FirmwareUpdateFragment();
            case SMTPMessage.RETURN_HDRS /*2*/:
                return new LanguageSelectionStartFragment();
            case ListInfo.INDETERMINATE /*3*/:
                return new AppCheckUpdateFragment();
            case SMTPMessage.NOTIFY_DELAY /*4*/:
                return new EnableNotificationsFragment();
            default:
                return null;
        }
    }

    private int currentStep() {
        if (this.mOnboardingStepIndex >= this.mOnboardingSequence.length) {
            return 0;
        }
        return this.mOnboardingSequence[this.mOnboardingStepIndex];
    }

    public void switchScreenFragment(Fragment fragment) {
        switchFragment(fragment);
    }

    public void switchToNoConnectivityFragment() {
        switchFragment(new NoConnectivityFragment(), false, false, true);
    }

    private void redirectToConnectionManager() {
        if (this.mInConnectionManager) {
            Trace.verbose(TAG, "Not redirecting to CMF; already there");
            return;
        }
        Trace.debug(TAG, "Redirecting to CMF");
        Toast.makeText(this, getString(R.string.my_pebble_no_device_connected), 1).show();
        this.mInConnectionManager = true;
        switchFragment(new ConnectionManagerFragment());
    }

    public static boolean isOnboardingRequired() {
        return getOnboardingSequence() != null;
    }

    static int[] getOnboardingSequence(int applicationOnboardingVersion, boolean isRunningRecoveryFw, PblDevice device, FirmwareVersion firmwareVersion, int deviceOnboardingVersion) {
        boolean isFreshInstall;
        boolean isLanguageAvailable = true;
        if (applicationOnboardingVersion < 0) {
            isFreshInstall = true;
        } else {
            isFreshInstall = false;
        }
        if (isFreshInstall) {
            Trace.verbose(TAG, "Application not previously onboarded; must show onboarding");
            return getNewUserOnboardingSequence();
        }
        boolean isDisconnected;
        if (device == null) {
            isDisconnected = true;
        } else {
            isDisconnected = false;
        }
        if (isDisconnected) {
            Trace.verbose(TAG, "Device is disconnected but application has been onboarded: don't show onboarding");
            return null;
        } else if (isRunningRecoveryFw) {
            Trace.verbose(TAG, "Device is running recovery firmware: needs onboarding");
            return getPrfSequence();
        } else if (firmwareVersion.compareTo(new FirmwareVersion("2.0", 0)) < 0) {
            Trace.verbose(TAG, "Device is running 1.x firmware: needs onboarding");
            return getMigrationOnboardingSequence();
        } else if (deviceOnboardingVersion == 1) {
            Trace.verbose(TAG, "Device has been fully onboarded to latest onboarding version: does not need onboarding");
            return null;
        } else {
            Trace.verbose(TAG, "Device is not fully onboarded but is 2.0+; Showing onboarding only if language packs are required");
            if (!PebbleCapabilities.remoteSupportsLanguagePacks(firmwareVersion)) {
                return null;
            }
            if (ConnectedDevice.getSupportedLanguagesCount() <= 0) {
                isLanguageAvailable = false;
            }
            if (isLanguageAvailable) {
                Trace.verbose(TAG, "Languages available");
                return getLanguageSelectionSequence();
            }
            Trace.info(TAG, "No languages available");
            return null;
        }
    }

    private static int[] getOnboardingSequence() {
        boolean isRunningRecovery;
        PblDevice device;
        FirmwareVersion firmwareVersion;
        int deviceOnboardingVersion;
        PblDeviceRecord record = PebbleApplication.getConnectedDeviceRecord();
        int appOnboardingVersion = OnboardingPreferences.getApplicationOnboardingVersion();
        if (record == null) {
            isRunningRecovery = true;
            device = null;
            firmwareVersion = null;
            deviceOnboardingVersion = -1;
        } else {
            isRunningRecovery = record.isRunningRecoveryFw;
            device = record.pblDevice;
            firmwareVersion = record.fwVersion;
            deviceOnboardingVersion = OnboardingPreferences.getOnboardingVersionFromPreferences(device);
        }
        Trace.debug(TAG, "getOnboardingSequence(" + appOnboardingVersion + ", " + isRunningRecovery + ", " + device + ", " + firmwareVersion + ", " + deviceOnboardingVersion + ")");
        return getOnboardingSequence(appOnboardingVersion, isRunningRecovery, device, firmwareVersion, deviceOnboardingVersion);
    }

    static int[] getNewUserOnboardingSequence() {
        return ONBOARDING_SEQUENCE_NEW_USER;
    }

    static int[] getMigrationOnboardingSequence() {
        return ONBOARDING_SEQUENCE_MIGRATION;
    }

    static int[] getPrfSequence() {
        return ONBOARDING_SEQUENCE_PRF;
    }

    static int[] getLanguageSelectionSequence() {
        return ONBOARDING_SEQUENCE_LANGUAGE_SELECTION;
    }
}
